# model_runner.py
# import subprocess
# import os
# model_runner.py
import subprocess
import os
import numpy as np

def run_deepfake_model(video_path):
    txt_path = os.path.abspath("single_video.txt")
    print(f"📌 写入测试视频路径到 single_video.txt: {txt_path}")

    with open(txt_path, 'w') as f:
        f.write(video_path.strip() + '\n')
    
    # 设置输出目录
    output_dir = os.path.abspath("save")
    os.makedirs(output_dir, exist_ok=True)

    # 拼接命令
    cmd = f"python detect1.py --test_video_path {txt_path} --device cuda:0 --max-len 50 --n_workers 4 --bs 1 --lam 0 --output_dir {output_dir}"
    print(f"📌 正在执行模型命令：{cmd}")

    try:
        result = subprocess.run(cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("📌 模型输出 stdout：")
        print(result.stdout.decode())
        print("📌 模型输出 stderr：")
        print(result.stderr.decode())
    except subprocess.CalledProcessError as e:
        print("❌ 模型运行出错：")
        print(e.stderr.decode())
        return None

    # 获取识别分数
    score_path = os.path.join(output_dir, "testing_scores.npy")
    print(f"📌 尝试读取模型输出得分文件: {score_path}")
    
    if os.path.exists(score_path):
        try:
            scores = np.load(score_path)
            print(f"✅ 成功读取得分: {scores}")
            if isinstance(scores, (list, np.ndarray)) and len(scores) > 0:
                score = float(scores[0])
                return score
            else:
                print("❌ scores 数组为空")
                return None
        except Exception as e:
            print(f"❌ 读取得分文件出错: {e}")
            return None
    else:
        print("❌ 未找到 testing_scores.npy")
        return None



# def run_deepfake_model(video_path):
#     txt_path = os.path.abspath("single_video.txt")
    
#     # 写入 single_video.txt
#     with open(txt_path, 'w') as f:
#         f.write(video_path + '\n')
    
#     # 调用 detect1.py
#     cmd = f"python detect1.py --test_video_path {txt_path} --device cuda:0 --max-len 50 --n_workers 4 --bs 1 --lam 0 --output_dir save"
    
#     try:
#         result = subprocess.run(cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#         print(result.stdout.decode())
#     except subprocess.CalledProcessError as e:
#         print("模型运行出错：", e.stderr.decode())
#         return None

#     # 获取识别分数（从save/testing_scores.npy）
#     score_path = os.path.join("save", "testing_scores.npy")
#     if os.path.exists(score_path):
#         scores = np.load(score_path)
#         score = float(scores[0])
#         return score
#     else:
#         return None
